# movie_app/forms.py
from django import forms
from .models import Movie
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

class MovieForm(forms.ModelForm):
    class Meta:
        model = Movie
        fields = '__all__'

    def clean(self):
        cleaned_data = super().clean()
        poster = cleaned_data.get('poster')
        poster_image = cleaned_data.get('poster_image')
        
        # 确保至少提供一种海报方式
        if not poster and not poster_image:
            raise forms.ValidationError("必须提供海报图片URL或上传图片文件")
        
        # 如果提供了URL，验证其有效性
        if poster:
            validator = URLValidator()
            try:
                validator(poster)
            except ValidationError:
                raise forms.ValidationError("请输入有效的图片URL")
        
        return cleaned_data
